package com.sfac.springCloudAccount.dao;

import com.sfac.account.User;
import com.sfac.common.vo.Search;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * UserDao
 */
@Mapper
@Repository
public interface UserDao {

	@Insert("insert into account_user (user_name, password, user_image, create_date) " +
			"values (#{userName}, #{password}, #{userImage}, #{createDate})")
	@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
	void insertUser(User user);

	@Update("update account_user set user_name = #{userName}, user_image = #{userImage} where id = #{id}")
	void updateUser(User user);

	@Delete("delete from account_user where id = #{id}")
	void deleteUserById(int id);

	@Select("select * from account_user where id = #{id}")
	@Results(id = "userResults", value = {
			@Result(property="id", column = "id"),
			@Result(property = "roles",
					column = "id",
					javaType = List.class,
					many = @Many(select = "com.sfac.springCloudAccount.dao.RoleDao.getRolesByUserId"))
	})
	User getUserById(int id);

	@Select("select * from account_user where user_name = #{userName} limit 1")
	User getUserByUserName(String userName);

	@Select("select * from account_user where user_name=#{userName} and password = #{password} limit 1")
	User getUserByUserNameAndPassword(@Param("userName") String userName, @Param("password") String password);

	@Select("<script>"
			+ "select * from account_user "
			+ "<where> "
			+ "<if test='keyword != \"\" and keyword != null'>"
			+ " and (user_name like '%${keyword}%') "
			+ "</if>"
			+ "</where>"
			+ "<choose>"
			+ "<when test='sort != \"\" and sort != null'>"
			+ " order by ${sort} ${direction}"
			+ "</when>"
			+ "<otherwise>"
			+ " order by id desc"
			+ "</otherwise>"
			+ "</choose>"
			+ "</script>")
	List<User> getUsersBySearch(Search search);
}
